<?php
/* 
 *  The MIT License
 * 
 *  Copyright 2011 http://
 * 
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 * 
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 * 
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *  THE SOFTWARE.
 */

/**
 * Utility per la gestione delle lingue accettate dal client dell'utente.
 *
 * @author Fabrizio Filieri
 */
class BXDHttpLang
{
    private $langs;

	/**
	 * Inizializza la classe di gestione delle lingue del client utente.
	 */
	public function __construct()
	{
		$this->langs = array();
		
		if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
		{
		    preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_parse);

			if (count($lang_parse[1]))
			{
				$this->langs = array_combine($lang_parse[1], $lang_parse[4]);

				foreach ($this->langs as $lang => $val)
				{
					if ($val === '') $this->langs[$lang] = 1;
				}

				arsort($this->langs, SORT_NUMERIC);
			}
		}
	}

	/**
	 * Ritorna l'array associativo con le lingue accettate dal client dell'utente.
	 *
	 * @return array l'array associativo con le lingue accettate dal client dell'utente
	 */
	public function getLangs()
	{
		return $this->langs;
	}

	/**
	 * Ritorna la lingua preferita dell'utente.
	 *
	 * @return string la prima lingua impostata nel client dell'utente
	 */
	public function getFirstLang()
	{
		if (count($this->langs) > 0)
		{
			$key = key($this->langs);

			return substr($key, 0, 2);
		}
		else
			return false;
	}

	/**
	 * Ritorna la prima nazione impostata nel client dell'utente.
	 * 
	 * @return string la prima nazione impostata nel client dell'utente
	 */
	public function getFirstCountry()
	{
		if (count($this->langs) > 0)
		{
			$key = key($this->langs);

			return substr($key, 3, 2);
		}
		else
			return false;
	}

}
?>
